import { DictionaryType, requestDict } from "../../../common/dictionary/dictionary-type.js";
import penentregsApi from '../../../common/api/food/penentregs.api.js'
import { uploadFile, requestFilePath, publicFileDraw, sliceFileName } from "../../../common/api/file-request.js";
import doT from '../../../../vendor/template/doT.js';

(function (window, document, $) {
    let _vm, getEntryInfo = [], pigDetails = [], pigDetailsInfo = []
    const PartnerSvcUrl = Utils.CurDomain.PartnerSvcUrl;
    const addsaleTemplate = doT.template($('#addpigType-template').text());

    $(function () {
        _vm = new Vue({
            el: "#saleordersentry-form",
            data() {
                return {
                    entries: [{
                        "seq": "",
                        "penNo": "",
                        "num": "",
                        "altdSltrSupp": {
                            "id": "",
                            "name": "",
                            "numCode": "",
                            "phone": "",
                        },
                        "prodLine": {
                            "id": "",
                            "name": "",
                        },
                        "attaches": "",
                        "remark": "",
                        "uploadCount": 0,
                        "attachesStr": [],
                    }],
                    pigDetails: []
                }
            },
            mounted() {
                let url = location.href
                let params = {} // url参数
                for (let key of (new URL(url)).searchParams.entries()) {
                    key[1] ? params[key[0]] = key[1] : ''
                }
                if (params.isEdit == 'true') {
                    document.title = '入圈登记分录 - 编辑'
                }
            },
            methods: {
                submit() {
                    let { altdSltrSupp, prodLine, penNo, num } = _vm.entries[0]
                    if (!Utils.IsNotNull(altdSltrSupp.name || altdSltrSupp.text)) {
                        return $.toptip(`请选择附属代宰户!`, 'warning');
                    }
                    if (!Utils.IsNotNull(prodLine.id)) {
                        return $.toptip(`请选择生产线!`, 'warning');
                    }
                    if (!Utils.IsNotNull(penNo)) {
                        return $.toptip(`请输入圈号!`, 'warning');
                    }
                    if (!Utils.IsNotNull(num)) {
                        return $.toptip(`请输入入圈头数!`, 'warning');
                    }
                    if (!(/(^[1-9]\d*$)/.test(num))) {
                        return $.toptip(`入圈头数必须为大于0的整数!`, 'warning');
                    }
                    savetips({ ..._vm.entries[0] })
                }
            }
        });
        $(document).on('mousedown', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $(document).on('focus', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
        _initCommand();
    });

    // 初始化数据
    const _initCommand = async () => {
        getEntryInfo = JSON.parse(Utils.GetSessionStorage("getEntryInfo")) || []
        let isEdit = JSON.parse(getUrlKey('isEdit'))
        let seqId = getUrlKey('index')
        // 编辑时赋值
        if (isEdit) {
            let datas = getEntryInfo.find(item => item.seq == seqId)
            const propertiesToCopy = ["penNo", "num", "altdSltrSupp", "prodLine", "attaches", "remark"];
            propertiesToCopy.reduce((obj, prop) => {
                _vm.entries[0][prop] = datas[prop];
            }, {});

            // 附件
            _vm.entries[0].attachesStr = []
            let editImage = []
            if (Utils.IsNotNull(datas.attachesStr)) {
                datas.attachesStr.forEach(item => {
                    editImage.push({
                        "imageId": item.imageId
                    })
                })
                _images(editImage)
                _vm.entries[0].uploadCount = datas.attachesStr.length
            }
            else if (Utils.IsNotNull(datas.attaches) && Utils.IsNotNull(isEdit)) {
                datas.attaches.split(',').forEach(item => {
                    editImage.push({
                        "imageId": item
                    })
                })
                _images(editImage)
                _vm.entries[0].uploadCount = datas.attaches.split(',').length
            }

        }
        uploadInit()

        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            location.href = `../penentregs/addpenentregs.html?v=${Utils.GetTime()}`;
        });

        // 附属代宰户
        $('#afltdSltrSupp').select2({
            allowClear: true,
            language: "zh-CN",
            tags: true,
            placeholder: '请选择附属代宰户...', //默认文字提示
            ajax: {
                url: `${PartnerSvcUrl}/sltrsupps/by/q`,
                dataType: 'json',
                type: 'GET',
                beforeSend: Utils.AjaxBeforeSend,
                data: function (params) {
                    if (Utils.IsNotNull(params.term)) {
                        return {
                            Status: true,
                            SearchInfo: params.term,
                            PageSize: 10,
                            PageIndex: (params.page || 1) - 1
                        };
                    } else {
                        return {
                            Status: true,
                            PageSize: 10,
                            PageIndex: (params.page || 1) - 1
                        };
                    }
                },
                cache: true,
                delay: 600,//等待用户输入完后的 在等250毫秒 进行搜索
                processResults: function (data, params) {
                    params.page = params.page || 1;
                    let _data = data.data.items.map(item => {
                        item.text = `${item.name}(${item.numCode})`;
                        return item;
                    });
                    return {
                        results: _data,// 后台返回的数据集
                        pagination: {
                            more: params.page < data.data.totalPages// 总页数为10，那么1-9页的时候都可以下拉刷新
                        }
                    };
                },
                // minimumInputLength: 1,
            }
        });
        $('#afltdSltrSupp').setSelectValue(_vm.entries[0].altdSltrSupp.id || _vm.entries[0].altdSltrSupp.name, _vm.entries[0].altdSltrSupp.name)
        // 选择代宰户
        $('#afltdSltrSupp').on('select2:select', async function (e) {
            if ($('#afltdSltrSupp').select2('data')[0].id == $('#afltdSltrSupp').select2('data')[0]?.text) {
                _vm.entries[0].altdSltrSupp.id = "";
                _vm.entries[0].altdSltrSupp.name = $('#afltdSltrSupp').select2('data')[0].text
            } else {
                _vm.entries[0].altdSltrSupp.id = $('#afltdSltrSupp').select2('data')[0].id
                _vm.entries[0].altdSltrSupp.name = $('#afltdSltrSupp').select2('data')[0].name
            }
            _vm.entries[0].altdSltrSupp.numCode = $('#afltdSltrSupp').select2('data')[0].numCode || ""

            var data = e.params.data; // 获取选中项的数据
            var text = data.text; // 获取选中项的文本
            var saleOrgsinfo = cutstr(text, 20); // 截取字符串
            $(this).select2('val', data.id); // 假设您想根据ID设置选中值
            $(this).next('.select2-container').find('.select2-selection__rendered').text(saleOrgsinfo);
            // let suppInfo = await penentregsApi.queryDetail(data.id)
            // _vm.entries[0].altdSltrSupp.phone = suppInfo.phone
        });
        //生产线
        let prodlinesArr = await penentregsApi.getProdlines()
        $(`#prodLine`).select2({
            placeholder: '请选择生产线...', //默认文字提示
            language: "zh-CN",//汉化
            allowClear: true,//允许清空
            data: prodlinesArr.map(item => {
                return {
                    id: item.id,
                    text: `${item.name}`,
                    name: item.name
                }
            }),
        });
        $('#prodLine').setSelectValue(_vm.entries[0].prodLine.id, _vm.entries[0].prodLine.name)
        $('#prodLine').on('select2:select', async function (e) {
            _vm.entries[0].prodLine.id = $('#prodLine').select2('data')[0].id
            _vm.entries[0].prodLine.name = $('#prodLine').select2('data')[0].name
        });

        // 猪只明细
        // 点击入圈头数 弹出猪只明细
        $('#penNum').on('click', function () {
            $("#report-contact").popup();
        })
        // 猪只类型
        let foodpigType = await requestDict(DictionaryType.FOOD_PIG_TYPE)
        let indexNum = 0
        // 猪只明细 编辑
        pigDetailsInfo = JSON.parse(Utils.GetSessionStorage("pigDetailsInfo")) || []
        let pigDetailsEdit = pigDetailsInfo.filter(item => item.pereSeq == seqId)
        if (Utils.IsNotNull(pigDetailsEdit)) {
            indexNum = pigDetailsEdit.length
            pigDetailsEdit.map((item1, index) => {
                $('#content').append(addsaleTemplate([{ 'seq': index + 1 }]))
                // 猪只类型
                $(`#pigType_${index + 1}`).select2({
                    minimumResultsForSearch: -1,
                    placeholder: '请选择猪只类型...', //默认文字提示
                    language: "zh-CN",//汉化
                    allowClear: true,//允许清空
                    data: foodpigType.data.map(item => {
                        return {
                            id: item.value,
                            text: item.displayName
                        }
                    })
                })
                $(`#pigType_${index + 1}`).setSelectValue(item1.pigType, item1.pigTypeName)
                $(`#pigQty_${index + 1}`).val(item1.qty)
            })
        }
        // 猪只明细  新增分录
        $('#add-pigType').on('click', function () {
            indexNum++
            $('#content').append(addsaleTemplate([{ 'seq': indexNum }]));
            // 猪只类型
            $(`#pigType_${indexNum}`).select2({
                minimumResultsForSearch: -1,
                placeholder: '请选择猪只类型...', //默认文字提示
                language: "zh-CN",//汉化
                allowClear: true,//允许清空
                data: foodpigType.data.map(item => {
                    return {
                        id: item.value,
                        text: item.displayName
                    }
                }),
            });
            $(`#pigType_${indexNum}`).setSelectValue()
            let defaultInf = foodpigType.data.filter(item => item.isDefault == true)
            $(`#pigType_${indexNum}`).setSelectValue(defaultInf[0]?.value, defaultInf[0]?.displayName);
        })

        // 关闭键盘
        // $(document).on('click', '.select2-selection', function () {
        //     document.activeElement.blur();
        // })



        // 猪只明细 取消
        $('#cancelSub').on('click', function () {
            $.closePopup();
        })

        // 猪只明细 确定
        $('#subEmployees').on('click', function () {
            pigDetails = []
            $('#content').find('select').each((idnex, item) => {
                pigDetails.push({
                    "seq": idnex,
                    "pigTypeName": $(item).select2('data')[0]?.text,
                    "pigType": $(item).select2('data')[0]?.id,
                    "qty": $('#content').find('input').eq(idnex).val(),
                    "pereSeq": seqId
                })
            })

            const nonewArr = pigDetails.map(item => item.pigType);
            const noarrSet = new Set(nonewArr);
            if (noarrSet.size != pigDetails.length) {
                $.toptip('猪只类型重复，请重新选择！', 'warning');
                return
            }
            else {
                let totalCount = 0
                let isValid = pigDetails.every(item => {
                    if (!(/(^[1-9]\d*$)/.test(item.qty))) {
                        $.toptip(`猪只数量必须为大于0的整数!`, 'warning');
                        return false; // 立即停止遍历并返回false
                    }
                    return true; // 如果qty是有效的整数，继续遍历
                });
                if (isValid) {
                    pigDetails.map(item => {
                        totalCount += Number(item.qty)
                    })
                    _vm.entries[0].num = totalCount
                    $.closePopup();
                }
            }
            pigDetailsInfo = pigDetailsInfo.filter(item => item.pereSeq != seqId)
            pigDetailsInfo.push(...pigDetails)
        })
        // 猪只明细 删除
        $(document).on('click', 'div[data-flag=table-click-delete]', function () {
            let seq = $(this).data('index')
            $('#content').find(`.item-box-${seq}`).remove()
        })
    }

    // 附件上传
    const uploadInit = () => {
        // 初始化上传组件
        weui.uploader('#uploader', {
            url: '',
            auto: false,
            type: 'file',
            compress: { isNoTCompress: true },
            onBeforeQueued: function (files) {
                // `this` 是轮询到的文件, `files` 是所有文件
                // if (["image/jpg", "image/jpeg", "image/png"].indexOf(this.type) < 0) {
                //     $.toptip('请上传图片', 'warning');
                //     return false; // 阻止文件添加
                // }
                if (this.size > 8 * 1024 * 1024) {
                    $.toptip('请上传不超过8M的文件', 'warning');
                    return false;
                }
                $.showLoading('上传中..');
                _vm.entries[0].uploadCount = ++_vm.entries[0].uploadCount;
                if (_vm.entries[0].uploadCount == 3) {
                    $('.weui-uploader__input-box').hide();
                }
            },
            onQueued: function () {
                let formFile = new FormData();
                let upFiles = this;
                let file = publicFileDraw(this.name, _vm);
                if (file != false && file != undefined) {
                    formFile.append('apiobjfile', new window.File([this], file, { type: this.type }));
                    _uploadFileDraw(formFile, upFiles, _vm, file);
                }
                //确认提交
                $('.weui-dialog__btn').on('click', function () {
                    if ($(this)[0].innerHTML == '确认') {
                        let fileName = sliceFileName(upFiles);
                        let newfile = publicFileDraw(fileName, _vm);
                        if (newfile != false && newfile != undefined) {
                            formFile.append('apiobjfile', new window.File([upFiles], newfile, { type: upFiles.type }));
                            _uploadFileDraw(formFile, upFiles, _vm, newfile);
                        }
                    }
                });
                return true;
            }
        });
        $('#uploaderFiles').click(function (e) {
            let target = e.target;
            while (!target.classList.contains('weui-uploader__file') && target) {
                target = target.parentNode;
            }
            if (!target) return;
            //从图片对应的li标签中获得所需属性
            let gallery = weui.gallery($(target).attr('data-url'), {
                className: 'custom-name',
                onDelete: function () {
                    //删除图片的回调
                    $.confirm({
                        title: '删除提示',
                        text: '确定删除该图片？',
                        onOK: function () {
                            let _id = $(target).attr('data-id');
                            _vm.entries[0].attachesStr = _vm.entries[0].attachesStr.filter(item => item.id != _id);
                            _vm.entries[0].uploadCount = --_vm.entries[0].uploadCount;
                            target.remove();
                            gallery.hide();
                            // 添加3张后隐藏上传按钮
                            if (_vm.entries[0].uploadCount == 3) {
                                $(".weui-uploader__input-box").hide();
                            } else {
                                $(".weui-uploader__input-box").show();
                            }
                        },
                        onCancel: function () {
                        }
                    });
                }
            });
        });
    }
    // 附件上传 66
    const _uploadFileDraw = (formFile, upFiles, _vm, newName) => {
        uploadFile(formFile).then(async res => {
            if (res.isSucceed) {
                let imageurl = await requestFilePath(res.data)
                let _list = _vm.entries[0].attachesStr;
                _list.push({
                    id: $("#uploaderFiles li").length,
                    imageId: res.data,
                    url: imageurl.data,
                });
                _vm.entries[0].attachesStr = _list;
                $("#uploaderFiles li").each(function (i) {
                    $(this).attr('data-id', _vm.entries[0].attachesStr[i].id);
                    $(this).attr('data-image-id', _vm.entries[0].attachesStr[i].imageId);
                    $(this).attr('data-url', _vm.entries[0].attachesStr[i].url);
                    $(this).css({ 'background-image': `url(${_vm.entries[0].attachesStr[i].url})` });
                });
                $('.weui-uploader__file-content').hide();
                $('.weui-uploader__file').removeClass('weui-uploader__file_status');
            }
        }).catch(res => {
            $("#uploaderFiles li").eq($("#uploaderFiles li").length - 1).remove();
            _vm.entries[0].uploadCount = --_vm.entries[0].uploadCount;
            $.toptip(res.msg, 'error');
        }).finally(_ => {
            $.hideLoading();
            $.closeModal();
        });
    }
    // 编辑回显
    const _images = async (file) => {
        let _imag = file;
        if (_imag) {
            let _sun = 0;
            for (let i = 0; i < _imag.length; i++) {
                ++_sun;
                await requestFilePath(_imag[i].imageId).then(_res => {
                    _vm.entries[0].attachesStr.push({
                        id: _sun,
                        url: _res.data,
                        imageId: _imag[i].imageId,
                    });
                    if (_res.isSucceed) {
                        let _li;
                        _li = `<li class="weui-uploader__file" data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i].imageId}" style="background-image: url(${_res.data}) "></li>`;
                        $('#uploaderFiles').append(_li);
                    }
                });
            }
            if (_sun == 3) {
                $(".weui-uploader__input-box").hide();
            }
            _vm.entries[0].uploadCount = _sun;
        }
    }
    // 保存提示
    const savetips = (data) => {
        let savetype
        if (Utils.IsNotNull(getUrlKey("isEdit"))) {
            savetype = '修改'
        }
        else {
            savetype = '保存'
        }

        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
    				<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
    					<div>是否确认${savetype}该分录？</div>
    				</div>`,
            buttons: [
                {
                    text: "取消", className: "default", onClick: function () {
                        $.closeModal();
                    }
                },
                {
                    text: "保存", onClick: function () {
                        let seq = parseInt(getUrlKey('index'))
                        let isEdit = JSON.parse(getUrlKey('isEdit'))

                        let imageArr = []
                        _vm.entries[0].attachesStr.forEach(item => {
                            imageArr.push(item.imageId)
                        })
                        let attachesStrAdd = imageArr.join(',')
                        data.attaches = attachesStrAdd
                        // 新增
                        if (!isEdit) {
                            getEntryInfo.push(data)
                        }
                        // 编辑
                        else if (isEdit) {
                            getEntryInfo[seq] = data
                        }
                        getEntryInfo.map((item, index) => {
                            item.seq = index
                        })
                        // 存入SessionStorage
                        JSON.stringify(Utils.SetSessionStorage("getEntryInfo", getEntryInfo))
                        JSON.stringify(Utils.SetSessionStorage("pigDetailsInfo", pigDetailsInfo))
                        location.href = `./addpenentregs.html?v=${Utils.GetTime()}`;
                        $.closeModal();
                    }
                }
            ]
        });
    }

    // 获取地址栏的参数
    const getUrlKey = (name) => {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }
    //解决字段过长问题
    const cutstr = (str, len) => {
        var str_length = 0;
        var str_len = 0;
        var str_cut = new String();
        str_len = str.length;
        for (var i = 0; i < str_len; i++) {
            var a = str.charAt(i);
            str_length++;
            if (escape(a).length > 4) {
                //中文字符的长度经编码之后大于4 
                str_length++;
            }
            str_cut = str_cut.concat(a);
            if (str_length >= len) {
                str_cut = str_cut.concat("...");
                return str_cut;
            }
        }
        //如果给定字符串小于指定长度，则返回源字符串； 
        if (str_length < len) {
            return str;
        }
    }

})(window, document, jQuery)